<?php
/**
 * 国内库存
 * (model)
 */

namespace App\Models\Inventory;

use App\Models\Basics\SysArea;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class InventoryCn extends Model
{
    protected $table = 'inventory_cn';

    protected $guarded = [];

    public $timestamps = false;

    public function area(){
        return $this->belongsTo(SysArea::class, 'area_id');
    }

    /**
     * 验证产品是否有库存
     * @param $pSkuId
     * @return bool
     */
    public static function existInventory($pSkuId){
        $count = self::query()
            ->where('psku_id',$pSkuId)
            ->where(function ($query){
                $query->where('instant','>',0)
                    ->orWhere('transit','>',0)
                    ->orWhere('reserve','>',0);
            })
            ->count();
        return $count > 0 ? true : false;
    }

    public static function existTransit($pSkuId){
        $count = self::query()
            ->where('psku_id',$pSkuId)
            ->where('transit','>',0)
            ->count();
        return $count > 0 ? true : false;
    }

    /**
     * 获取国内仓sku的在库库存 （站外库存、公共库存、其他站点库存）
     * @param $pSkuId
     * @param int $maxNum
     * @return array
     */
    public static function getCnAeraInventory($pSkuId, $maxNum = 0){
        $outId = SysArea::getSysOutAreaIdByArea();
        $publicId = SysArea::getSysAreaIdByArea();
        $outInstant = AreaCn::getInstant($outId,$pSkuId);
        $publicInstant = PublicCn::getInstant($pSkuId);
        $otherInstant = self::query()
            ->whereNotIn('area_id', [$outId,$publicId])
            ->where('psku_id', $pSkuId)
            ->sum('instant');
        $sum = $outInstant + $publicInstant + $otherInstant;
        if($sum < $maxNum){
            return [];
        }else{
            return [
                'OUT' => $outInstant,
                'PUBLIC' => $publicInstant,
                'OTHER' => $otherInstant
            ];
        }
    }

}
